package com.ray.activiti.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.activiti.engine.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.ray.activiti.common.Constant.SelectType;
import com.ray.activiti.service.ActModelerService;
import com.ray.activiti.service.ExtendActBusinessService;
import com.ray.activiti.service.ExtendActFlowbusService;
import com.ray.activiti.service.ExtendActModelerService;
import com.ray.activiti.service.ExtendActNodesetService;
import com.ray.activiti.service.ExtendActNodeuserService;
import com.ray.activiti.service.ExtendActTasklogService;
import com.ray.activiti.table.entity.ExtendActModel;
import com.ray.activiti.table.entity.ExtendActNodeset;
import com.ray.activiti.table.entity.ExtendActTasklog;
import com.ray.activiti.util.DataGridUtil;
import com.ray.api.service.ActivitiApiService;
import com.ray.api.service.UcenterApiService;
import com.ray.auth.system.table.entity.Button;
import com.ray.auth.system.table.entity.User;
import com.xiaoleilu.hutool.util.ObjectUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import com.zjhc.flyhong.common.function.operator.LoginUser;
import com.zjhc.flyhong.common.function.operator.PageDto;
import com.zjhc.flyhong.common.web.Result;
import com.zjhc.web.controller.WebController;

/**
 * 类的功能描述. 流程办理相关操作
 * 
 * @Auther ray qray686898@163.com
 * @Date 2017/12/28
 * @代码参考或来自 https://github.com/huangxianyuan/hxyFrame
 */
@Controller
@RequestMapping("act/common")
public class ActController extends WebController {
	@Autowired
	UcenterApiService ucenterApiService;
	@Autowired
	ActivitiApiService activitiApiService;
	@Autowired
	ExtendActModelerService extendActModelService;
	@Autowired
	ActModelerService actModelerService;
	@Autowired
	ExtendActNodesetService nodesetService;
	@Autowired
	ExtendActNodeuserService nodeuserService;
	@Autowired
	ExtendActTasklogService tasklogService;
	@Autowired
	TaskService taskService;
	@Autowired
	ExtendActFlowbusService flowbusService;
	@Autowired
	ExtendActBusinessService businessService;

	/**
	 * 流程实例和用户选择
	 * 
	 * @param model
	 * @param code
	 * @param busId
	 * @param request
	 * @return
	 */
	@RequestMapping("userAndActView")
	public ModelAndView userAndActView(String menuId, String actKey, HttpServletRequest request,
			ModelAndView modelAndView) {
		modelAndView.addObject("actKey", actKey);
		modelAndView.setViewName("activiti/common/view");
		return modelAndView;
	}

	/**
	 * 用户选择页面
	 * 
	 * @param model
	 * @param code
	 * @param busId
	 * @param request
	 * @return
	 */
	@RequestMapping("userView")
	public ModelAndView user(String menuId, String nodeId, HttpServletRequest request, ModelAndView modelAndView) {
		LoginUser user = getLoginUser();
		// 查询页面拥有的资源
		Result<Map<String, List<Button>>> buttonsResult = ucenterApiService.queryUserButtonsWithMenu(user, menuId);
		if (buttonsResult.codeSuccess()) {
			modelAndView.addObject("buttons", buttonsResult.getData());
		}
		modelAndView.addObject("nodeId", nodeId);
		modelAndView.setViewName("activiti/common/user");
		return modelAndView;
	}

	/**
	 * 流程实例查询
	 * 
	 * @param model
	 * @param code
	 * @param busId
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("actQuery")
	@ResponseBody
	public ResponseEntity<Map<String, Object>> actQuery(String actKey, HttpServletRequest request) {
		LoginUser user = getLoginUser();
		PageDto<Map<String, Object>> pageDto = this.createJQPage(request);
		List<Map<String, Object>> defs = actModelerService.queryFlowsByActKey(actKey,user);
		for (Map<String, Object> map : defs) {
			ExtendActModel extendActModel = extendActModelService.queryByDeployId((String) map.get("deploymentId"));
			if (extendActModel != null) {
				map.put("name", extendActModel.getName());
				map.put("id", extendActModel.getBaid());
				map.put("actKey", actKey);
				map.put("modelId", extendActModel.getModelId());
				map.put("description", extendActModel.getDescription());

			}
		}
		pageDto.setRecords(defs);
		return doSuccess(DataGridUtil.dataConvert(pageDto));
	}

	/**
	 * 用户查询
	 * 
	 * @param model
	 * @param code
	 * @param busId
	 * @param request
	 * @return
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("userQuery")
	@ResponseBody
	public ResponseEntity<Map<String, Object>> userQuery(String nodeId, String deployId, HttpServletRequest request)
			throws IOException {
		PageDto<User> pageDto = this.createJQPage(request);
		LoginUser user = new LoginUser();
		user.setSuperManager(false);
		//获取当前节点的所属的租户
		ExtendActNodeset actNodeset = nodesetService.queryByNodeId(nodeId);
		ExtendActModel actModel =extendActModelService.queryByModelId(actNodeset.getModelId());
		user.setTenantId(actModel.getTenantid());
		/*
		 * if(StrUtil.isEmpty(nodeId) && !StrUtil.equals("0", deployId)){
		 * ActNode node = actModelerService.getStartFlowInfo(deployId); nodeId =
		 * node.getNodeId(); }
		 */
		if (StrUtil.isBlank(nodeId)) {
			return doSuccess(DataGridUtil.dataConvert(pageDto));
		}
		// 用户IDS
		List<String> userIds = nodeuserService.queryIds(SelectType.USER.getValue(), nodeId);
		userIds.add("deafult");
		// 角色IDS
		List<String> roleIds = nodeuserService.queryIds(SelectType.ROLE.getValue(), nodeId);
		roleIds.add("deafult");
		// 获取审批用户
		List<User> lists = ucenterApiService.queryUserList(userIds, roleIds, user);
		if (lists.isEmpty()) {
			// 显示执行人员信息
		}
		pageDto.setRecords(lists);
		return doSuccess(DataGridUtil.dataConvert(pageDto));
	}

	/**
	 * 审批信息
	 * 
	 * @param model
	 * @param code
	 * @param busId
	 * @param request
	 * @return
	 */
	@RequestMapping("applyView")
	public ModelAndView applyView(String menuId, String busId, HttpServletRequest request, ModelAndView modelAndView) {
		LoginUser user = getLoginUser();
		// 查询页面拥有的资源
		Result<Map<String, List<Button>>> buttonsResult = ucenterApiService.queryUserButtonsWithMenu(user, menuId);
		if (buttonsResult.codeSuccess()) {
			modelAndView.addObject("buttons", buttonsResult.getData());
		}
		modelAndView.addObject("busId", busId);
		modelAndView.setViewName("activiti/common/apply");
		return modelAndView;
	}

	/**
	 * 审批信息查询
	 * 
	 * @param model
	 * @param code
	 * @param busId
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("applyQuery")
	@ResponseBody
	public ResponseEntity<Map<String, Object>> applyQuery(String busId, HttpServletRequest request) {
		PageDto<ExtendActTasklog> pageDto = this.createJQPage(request);
		Map<String, Object> params = new HashMap<>();
		params.put("busId", busId);
		List<ExtendActTasklog> tasklogEntities = tasklogService.queryList(params);
		for (ExtendActTasklog log : tasklogEntities) {
			log.setAdvanceName(ucenterApiService.queryUserName(log.getAdvanceId()));
			log.setDealName(ucenterApiService.queryUserName(log.getDealId()));
		}
		pageDto.setRecords(tasklogEntities);
		return doSuccess(DataGridUtil.dataConvert(pageDto));
	}

	/**
	 * 用户查询
	 * 
	 * @param model
	 * @param code
	 * @param busId
	 * @param request
	 * @return
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("userAllQuery")
	@ResponseBody
	public ResponseEntity<Map<String, Object>> userAllQuery(HttpServletRequest request) throws IOException {
		PageDto<User> pageDto = this.createJQPage(request);
		LoginUser user = getLoginUser();
		pageDto = ucenterApiService.queryUserList(pageDto, new User(), user);
		return doSuccess(DataGridUtil.dataConvert(pageDto));
	}

	/**
	 * 用户查询
	 * 
	 * @param model
	 * @param code
	 * @param busId
	 * @param request
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("startNodeQuery")
	@ResponseBody
	public ResponseEntity<Result<Object>> startNodeQuery(String modelId, HttpServletRequest request)
			throws IOException {
		// 获取当前节点的
		ExtendActNodeset node = nodesetService.queryStartNodeByModelId(modelId);
		if (ObjectUtil.isNull(node)) {
			return doError("无法找到节点");
		}
		return doSuccess("", node);
	}

}
